import 'package:flutter/material.dart';
import 'package:flutter_chip/view/news/view_chatlist.dart';
import 'package:flutter_chip/view/news/view_msg.dart';

class NewsPage extends StatefulWidget {
  @override
  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  var tabs = ["消息", "聊天"];
  PageController pageController;
  TabController tabController;
  int page = 0;
  var isPageCanChanged = true;

  @override
  void initState() {
    super.initState();
    pageController = PageController(initialPage: this.page);
    tabController =
        TabController(length: tabs.length, vsync: this, initialIndex: 0);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        onPageChange(tabController.index, p: pageController);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          centerTitle: true,
          elevation: 0,
          backgroundColor: Theme.of(context).canvasColor,
          title: TabBar(
              controller: tabController,
              isScrollable: true,
              labelColor: Color(0xff333333),
              unselectedLabelColor: Color(0xff999999),
              indicatorColor: Color(0xff333333),
              indicatorSize: TabBarIndicatorSize.label,
              onTap: (value) {
                pageController.jumpToPage(value);
              },
              tabs: tabs.map((item) {
                return Tab(child: Text(item, style: TextStyle(fontSize: 16)));
              }).toList())),
      body: PageView(
          controller: pageController,
          onPageChanged: (index) {
            if (isPageCanChanged) {
              onPageChange(index);
            }
          },
          children: <Widget>[MsgPage(), ChatPage()]),
    );
  }

  ///页面滑动监听
  onPageChange(int index, {PageController p, TabController t}) async {
    if (p != null) {
      //判断是哪一个切换
      isPageCanChanged = false;
      await pageController.animateToPage(index,
          duration: Duration(milliseconds: 500), curve: Curves.ease);
      isPageCanChanged = true;
    } else {
      tabController.animateTo(index);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
